<?php

declare(strict_types=1);

namespace app\service\user\login;

use app\model\User;
use app\model\UserAuth;

class Oauth implements LoginInterface
{
    public function login(array $credentials): array
    {
        $openid = $credentials['openid'] ?? '';
        $unionid = $credentials['unionid'] ?? null;
        $platform = $credentials['platform'] ?? 'wechat_mp';

        // 1. 首先尝试通过unionid查找用户（如果提供了unionid）
        if ($unionid) {
            $userAuth = UserAuth::where('identity_type', $platform)
                ->where('unionid', $unionid)
                ->find();
            if ($userAuth) {
                // 更新openid（可能在不同平台登录）
                if ($userAuth->identifier != $openid) {
                    $userAuth->identifier = $openid;
                    $userAuth->save();
                }
                // 检查用户是否绑定了手机号
                if (empty($userAuth->user)) {
                    // 用户未绑定手机号，只返回 UserAuth 信息
                    return [
                        "status" => "need_bind_phone",
                        "user" => $userAuth,
                        "msg" => "需要绑定手机号以完成注册",
                    ];
                }
                $userAuth->user()->update(['last_login_time' => date('Y-m-d H:i:s')]);
                return  ["status" => "success", "user" => $userAuth->user];
            }
        }

        // 2. 然后尝试通过平台特定的openid查找用户
        $userAuth = UserAuth::where('identity_type', $platform)
            ->where('identifier', $openid)
            ->find();

        if ($userAuth) {
            // 如果有unionid但用户没有unionid记录，则补充
            if ($unionid && empty($userAuth->unionid)) {
                $userAuth->unionid = $unionid;
                $userAuth->save();
            }
            // 检查用户是否绑定了手机号
            if (empty($userAuth->user)) {
                // 用户未绑定手机号，只返回 UserAuth 信息
                return [
                    "status" => "need_bind_phone",
                    "user" => $userAuth,
                    "msg" => "需要绑定手机号以完成注册",
                ];
            }
            $userAuth->user()->update(['last_login_time' => date('Y-m-d H:i:s')]);
            return  ["status" => "success", "user" => $userAuth->user];
        }
        // 3. 如果没有找到用户
        // 创建一个临时的 UserAuth 对象用于后续绑定手机号
        $userAuth = new UserAuth([
            'identity_type' => $platform,
            'identifier' => $openid,
            'unionid' => $unionid,
            'credential'    => '',
        ]);
        return [
            "status" => "need_bind_phone",
            "user" => $userAuth, // 返回 UserAuth 对象供后续绑定手机号使用
            "msg" => "需要绑定手机号以完成注册",
        ];
    }

    public function getIdentifier(): string
    {
        return 'oauth';
    }
}
